package com.link.play.fit.ai.utils

import android.util.Log
import com.link.play.fit.ai.bean.BaseResponse
import retrofit2.HttpException
import java.io.IOException

object HttpResponse {
    // 封装请求方法
    suspend fun <T> safeApiCall(
        apiCall: suspend () -> BaseResponse<T>
    ): ApiResult<T> {
        return try {
            val response = apiCall()
            when {
                // 业务成功（根据实际业务码调整）
                response.status == 200 -> {
                    if (response.result?.data != null) {
                        ApiResult.Success(response.result.data)
                    } else {
                        // 处理 data 为 null 的异常情况
                        ApiResult.BusinessError(
                            status = 500,
                            message = "Data field is null"
                        )
                    }
                }
                // 业务失败
                else -> ApiResult.BusinessError(
                    status = response.status,
                    message = response.msg ?: "Business error"
                )
            }
        } catch (e: IOException) {
            // 网络层异常

            Log.e("Network", "IO error: ${e.message}")
            ApiResult.NetworkError
        } catch (e: HttpException) {
            // HTTP协议层异常（如404, 500等）
            val errorMsg = parseHttpError(e)
            Log.e("Network", "HTTP error: $errorMsg")
            ApiResult.HttpError(
                code = e.code(),
                message = errorMsg
            )
        } catch (e: Exception) {
            // 其他未知异常
            Log.e("Network", "Unexpected error: ${e.stackTraceToString()}")
            ApiResult.BusinessError(
                status = -1,
                message = "System error: ${e.message}"
            )
        }
    }

    // 解析HTTP错误详情
    private fun parseHttpError(e: HttpException): String {
        return try {
            e.response()?.errorBody()?.string() ?: "Unknown HTTP error"
        } catch (ex: Exception) {
            "Failed to parse error body"
        }
    }
}